package com.dhq.myapp

import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import com.bumptech.glide.Glide
import com.dhq.myapp.base.BaseActivity
import com.dhq.myapp.entity.DeviceConnectEvent
import com.dhq.myapp.ui.identity.IdentityActivity
import com.dhq.myapp.util.BluetoothHelper
import com.dhq.myapp.util.DataStorageUtils
import com.dhq.myapp.util.GlassOptionUtil
import com.dhq.myapp.util.IdentifyUtil
import com.dhq.myapp.util.LogUtil
import com.dhq.myapp.util.WifiUtil
import com.rokid.cxr.client.extend.CxrApi
import com.rokid.cxr.client.extend.callbacks.BluetoothStatusCallback
import com.rokid.cxr.client.extend.callbacks.PhotoPathCallback
import com.rokid.cxr.client.utils.ValueUtil
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MainActivity : BaseActivity(), View.OnClickListener {

    companion object {
//        const val TAG = "MainActivity"

        // Request Code
        const val REQUEST_CODE_PERMISSIONS = 100

        // Required Permissions
        private val REQUIRED_PERMISSIONS = mutableListOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.NEARBY_WIFI_DEVICES
//            Manifest.permission.READ_EXTERNAL_STORAGE,
//            Manifest.permission.WRITE_EXTERNAL_STORAGE
        ).apply {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                add(Manifest.permission.BLUETOOTH_SCAN)
                add(Manifest.permission.BLUETOOTH_CONNECT)
            }
        }.toTypedArray()
    }

    // Permission
    private val permissionGrantedResult = MutableLiveData<Boolean?>()

    // Bluetooth Helper
    private var bluetoothHelper: BluetoothHelper? = null
    private var mGlassOptionUtil: GlassOptionUtil? = null
    private var mWifiUtil: WifiUtil? = null

//    override fun onCreate(savedInstanceState: Bundle?) {
//        super.onCreate(savedInstanceState)
//        enableEdgeToEdge()
//        setContentView(R.layout.activity_main_lay)
//        init();
//        applyPermissions();
//
//    }

    private var tv_go_connect: TextView? = null;
    private var tv_glasses_info: TextView? = null;
    private var ll_connect_desc: View? = null;
    private var rl_token_photo: View? = null;
    private var rl_speech_recognition: View? = null;

    private var tv_file_path: TextView? = null;
    private var tv_file_name: TextView? = null;

    private var iv_indetity_result: ImageView? = null;
    private var tv_indetity_result: TextView? = null;


    private var isConnectWifi: Boolean = false


    override fun getLayoutId(): Int {
        return R.layout.activity_main_lay
    }

    override fun initView() {

        EventBus.getDefault().register(this);

        DataStorageUtils.initialize(this)

        tv_go_connect = findViewById<TextView>(R.id.tv_go_connect);
        tv_glasses_info = findViewById<TextView>(R.id.tv_glasses_info);
        ll_connect_desc = findViewById<TextView>(R.id.ll_connect_desc);
        rl_token_photo = findViewById<TextView>(R.id.rl_token_photo);
        rl_speech_recognition = findViewById<TextView>(R.id.rl_speech_recognition);

        tv_file_path = findViewById<TextView>(R.id.tv_file_path);
        tv_file_name = findViewById<TextView>(R.id.tv_file_name);

        iv_indetity_result = findViewById<ImageView>(R.id.iv_indetity_result);
        tv_indetity_result = findViewById<TextView>(R.id.tv_indetity_result);


        tv_go_connect?.setOnClickListener(this)
        ll_connect_desc?.setOnClickListener(this)
        rl_token_photo?.setOnClickListener(this)

    }

    override fun initData() {

        getHeaderUtil().hintLeftBack().setHeaderTitle("首页")
        init();

        applyPermissions();

        mWifiUtil = WifiUtil(object : WifiUtil.WifiListener {
            override fun onConnected() {
                isConnectWifi = true
                toast("连接wifi成功，可以传递数据了！")
            }

            override fun onDisconnected() {

            }

            override fun onFailed() {
                toast("连接wifi失败！")
            }
        })



        var socketUuid = DataStorageUtils.getStringValue("socketUuid","")
        var macAddress = DataStorageUtils.getStringValue("macAddress","")
        var bluetoothName = DataStorageUtils.getStringValue("bluetoothName","")


        if (!TextUtils.isEmpty(socketUuid) && !TextUtils.isEmpty(macAddress)){
            CxrApi.getInstance().connectBluetooth(this, socketUuid, macAddress, object : BluetoothStatusCallback {


                override fun onConnectionInfo(
                    socketUuid: String?, macAddress: String?, rokidAccount: String?, glassesType: Int
                ) {
                    if (socketUuid != null && macAddress != null) {
//                        CxrApi.getInstance().connectBluetooth(context, socketUuid, macAddress, this)
                    }
                }
                override fun onConnected() {
                    Log.d("BluetoothScanActivity11", "Connected")
                    runOnUiThread {
                        showDeviceConnectEvent(bluetoothName)
//                        EventBus.getDefault().post(DeviceConnectEvent(device))
                    }
                }
                override fun onDisconnected() {
                    Log.d("BluetoothScanActivity222", "Disconnected")
                    runOnUiThread {
//                    tv_status?.setText("连接断开");
//                    tvStatus.text = "设备已断开连接"
//                    btnSend.isEnabled = false
//                    btnScan.text = "重新扫描"
//                    btnScan.isEnabled = true
                    }
                }
                override fun onFailed(code: ValueUtil.CxrBluetoothErrorCode?) {
                    Log.e("BluetoothScanActivity33", "Failed: ${code}")
                    runOnUiThread {
//                    tv_status?.setText("连接失败");
//                    tvStatus.text = "连接失败: $code"
//                    btnSend.isEnabled = false
//                    btnScan.text = "重新扫描"
//                    btnScan.isEnabled = true
                    }
                }
            })
        }


    }

    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.tv_go_connect -> {
                //跳转蓝牙扫描界面
                val intent = Intent(this, BluetoothScanActivity::class.java)
                startActivity(intent)
            }

            R.id.ll_connect_desc -> {
                //跳转连接说明

            }

            R.id.rl_token_photo -> {
                //跳转拍照识别界面
                val intent = Intent(this, IdentityActivity::class.java)
                startActivity(intent)
                return;

//                //发送数据通知眼镜显示
//                var stauts = IdentifyUtil.openCustomView("")
//
//                Log.e("返回结果",stauts.toString())
//
//                return

                //跳转连接说明
                mGlassOptionUtil?.takePhoto(object : PhotoPathCallback {
                    override fun onPhotoPath(
                        status: ValueUtil.CxrStatus?,
                        path: String?
                    ) {
                        tv_file_path?.setText("同步文件路径:"+path!!)
                        getTokePhotoFile(path!!);
                    }
                })
//                if (isConnectWifi) {
//                    mGlassOptionUtil?.takePhoto(object : PhotoPathCallback {
//                        override fun onPhotoPath(
//                            status: ValueUtil.CxrStatus?,
//                            path: String?
//                        ) {
//                            tv_file_path?.setText("同步文件路径:"+path!!)
//                            getTokePhotoFile(path!!);
//                        }
//                    })
//                }else{
//                    var status = mWifiUtil?.initWifi()
//                    if (status == ValueUtil.CxrStatus.REQUEST_SUCCEED) {
//                        isConnectWifi = true;
//                        mGlassOptionUtil?.takePhoto(object : PhotoPathCallback {
//                            override fun onPhotoPath(
//                                status: ValueUtil.CxrStatus?,
//                                path: String?
//                            ) {
//                                tv_file_path?.setText("同步文件路径:"+path!!)
//                                getTokePhotoFile(path!!);
//                            }
//                        })
//                    }
//
//                }

            }

            R.id.rl_speech_recognition -> {
                //跳转连接说明
//                mGlassOptionUtil
            }
        }
    }

    fun showIndetifyResult(name: String ,imagePath:String){
        tv_indetity_result?.setText(name)
//        tv_indetity_result
        Glide.with(this).load(imagePath).into(iv_indetity_result!!)


    }


    fun getTokePhotoFile(path: String) {

        if (mWifiUtil?.getWiFiConnectionStatus()==true){
            //表示wifi连接成功
            mGlassOptionUtil?.getFile(path, object : GlassOptionUtil.SyncListener {
                //        mGlassOptionUtil?.getFileList(path, object : GlassOptionUtil.SyncListener {
                override fun onSyncStart() {

                    toast("获取数据开始")
                }

                override fun onSingleFileSynced(fileName: String?) {
                    toast("获取数据完成")
                    tv_file_name?.setText("同步文件后地址:"+fileName!!)


                    showIndetifyResult("老虎",fileName!!)

                }

                override fun onSyncFailed() {

                    toast("获取数据失败")
                }

                override fun onSyncFinished() {

                    toast("获取数据完成")
                }

            })
        }else{
            //表示wifi连接失败
            var status = mWifiUtil?.initWifi()

        }



    }

    /**
     * 申请权限
     */
    fun applyPermissions() {
        // Request Permissions
        permissionGrantedResult.postValue(null)
        requestPermissions(REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS)

        // Observe Permission Result
        permissionGrantedResult.observe(this) {
            if (it == true) {
                // Permission All Granted
//                bluetoothHelper.show
                Log.e("权限", "权限以通过")
                // 检查权限并开始初始化
//                bluetoothHelper?.permissionResult?.postValue(true)
//                bluetoothHelper?.checkPermissions()

            } else {
                Log.e("权限", "权限为通过")
                // Some Permission Denied or Not Started
            }
        }
    }

    fun init() {
        // 创建BluetoothHelper实例
        bluetoothHelper = BluetoothHelper(this, { initStatus ->
            // 处理初始化状态回调
            when (initStatus) {
                BluetoothHelper.Companion.INIT_STATUS.NotStart -> {
//                        Toast.makeText(this, "Bluetooth initialization not started", Toast.LENGTH_SHORT).show()
                }

                BluetoothHelper.Companion.INIT_STATUS.INITING -> {
                    Toast.makeText(this, "蓝牙初始化中", Toast.LENGTH_SHORT).show()
                }

                BluetoothHelper.Companion.INIT_STATUS.INIT_END -> {
                    Toast.makeText(this, "蓝牙初始化完成", Toast.LENGTH_SHORT).show()
                    // 初始化完成后可以开始扫描设备

                    scanDevices()
                    // bluetoothHelper?.startScan() // 注意：startScan()已经在BluetoothHelper内部调用
                }
            }
        }, {
            // 处理设备发现回调
            Toast.makeText(this, "发现新设备", Toast.LENGTH_SHORT).show()
            // 可以在这里更新UI，显示发现的设备
//                updateDeviceList()


        })
        mGlassOptionUtil = GlassOptionUtil(this)

    }

    private fun connectRokid(context: Context, device: BluetoothDevice) {
        CxrApi.getInstance().initBluetooth(context, device, object : BluetoothStatusCallback {


            override fun onConnectionInfo(
                socketUuid: String?, macAddress: String?, rokidAccount: String?, glassesType: Int
            ) {
                if (socketUuid != null && macAddress != null) {
                    CxrApi.getInstance().connectBluetooth(context, socketUuid, macAddress, this)
                }
            }
            override fun onConnected() {
                Log.d("BluetoothScanActivity", "Connected")
                runOnUiThread {
                    EventBus.getDefault().post(DeviceConnectEvent(device))
                }
            }
            override fun onDisconnected() {
                Log.d("BluetoothScanActivity", "Disconnected")
                runOnUiThread {
//                    tv_status?.setText("连接断开");
//                    tvStatus.text = "设备已断开连接"
//                    btnSend.isEnabled = false
//                    btnScan.text = "重新扫描"
//                    btnScan.isEnabled = true
                }
            }
            override fun onFailed(code: ValueUtil.CxrBluetoothErrorCode?) {
                Log.e("BluetoothScanActivity", "Failed: ${code}")
                runOnUiThread {
//                    tv_status?.setText("连接失败");
//                    tvStatus.text = "连接失败: $code"
//                    btnSend.isEnabled = false
//                    btnScan.text = "重新扫描"
//                    btnScan.isEnabled = true
                }
            }
        })
    }



    private fun tokenPhoto() {
        val photoPathResult = object : PhotoPathCallback {
            override fun onPhotoPath(
                status: ValueUtil.CxrStatus?, path: String?
            ) {
                if (status == ValueUtil.CxrStatus.RESPONSE_SUCCEED) {
                    //拍照成功

                    if (path != null) {
                        Log.e("MainActivity", "文件路径：" + path)
                    };

                } else if (status == ValueUtil.CxrStatus.RESPONSE_INVALID) {
                    //拍照失败

                } else if (status == ValueUtil.CxrStatus.RESPONSE_TIMEOUT) {
                    //拍照超时

                }
            }

        }
        mGlassOptionUtil?.takePhoto(photoPathResult)
    }


    /**
     * 更新设备列表
     */
    private fun updateDeviceList() {

//        bluetoothHelper.
//
//        bluetoothHelper?.let {\ helper ->
//            // 获取扫描到的设备
//            val scanResults = helper.scanResultMap
//            // 获取已配对的设备
//            val bondedDevices = helper.bondedDeviceMap
//
//            // 这里可以更新UI，显示设备列表
//            Toast.makeText(this, "Found ${scanResults.size} devices, Bonded: ${bondedDevices.size}",
//                Toast.LENGTH_SHORT).show()
//        }
    }

    /**
     * 手动开始扫描设备
     */
    @SuppressLint("MissingPermission")
    fun scanDevices() {
        bluetoothHelper?.startScan()
    }

    /**
     * 停止扫描设备
     */
    @SuppressLint("MissingPermission")
    fun stopScanDevices() {
        bluetoothHelper?.stopScan()
    }

    fun showDeviceConnectEvent(name: String){

        tv_go_connect?.visibility=View.GONE
        tv_glasses_info?.visibility=View.VISIBLE
        tv_glasses_info?.setText("已连接 "+name)
    }

    @SuppressLint("MissingPermission")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun showDevice(event: DeviceConnectEvent) {
        showDeviceConnectEvent(event.device.name)
//        tv_go_connect?.visibility=View.GONE
//        tv_glasses_info?.visibility=View.VISIBLE
//        tv_glasses_info?.setText("已连接 "+event.device.name)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        // 释放BluetoothHelper资源
        bluetoothHelper?.release()
    }


    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<out String>, grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CODE_PERMISSIONS.hashCode()) {
            val allGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }
            permissionGrantedResult.postValue(allGranted)
        }
    }

}
